import Vue from 'vue'

import Vuex from 'vuex'

import axios from 'axios'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    goodsList: []
  },
  mutations: {
    setGoodsList(state, newList){
      state.goodsList = newList
    }
  },
  actions: {
    async asyncSetGoodsList(store) {
      // 步骤：
      // 1、 发起ajax请求
      const resp = await axios({
        method: 'GET',
        url: 'https://www.escook.cn/api/cart'
      })
      // 2、 后台响应的数据 commit到 setGoodsList mutations中
      store.commit('setGoodsList', resp.data.list)
    }
  },
  getters: {
    totalCount(state){
      return state.goodsList.reduce((sum, obj) => {
        if(obj.goods_state) {
          sum += obj.goods_count
        }
        return sum
      }, 0)
    },
    totalPrice(state){
      return state.goodsList.reduce((sum, obj) => {
        if(obj.goods_state) {
          sum += obj.goods_count * obj.goods_price
        }
        return sum
      }, 0)
    }
  }
 })

 export default store